package com.baima46.utils;


import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * http工具类
 * @author ：yuan cong
 * @email : 749865308@qq.com
 * @date ：2020-12-07
 * @description：
 */
public class HttpUtil {

	public static HttpServletRequest getHttpServletRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	public static HttpServletResponse getHttpServletResponse() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
	}

	public static String getDomain(){
		HttpServletRequest request = getHttpServletRequest();
		StringBuffer url = request.getRequestURL();
		return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
	}

	public static String getOrigin(){
		HttpServletRequest request = getHttpServletRequest();
		return request.getHeader("Origin");
	}



	/**
	 * 下载请求设置
	 *
	 * @param request
	 * @param response
	 * @param displayFilename
	 * @throws UnsupportedEncodingException
	 */
	public static final void downloadInit(HttpServletRequest request, HttpServletResponse response, String displayFilename) throws UnsupportedEncodingException {
		String userAgent = request.getHeader("User-Agent");
		boolean isIE = (userAgent != null) && ((userAgent.toLowerCase().indexOf("msie") != -1)
				|| (userAgent.toLowerCase().indexOf("trident") != -1)
				|| (userAgent.toLowerCase().indexOf("edge") != -1));

		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "must-revalidate, no-transform");
		response.setDateHeader("Expires", 0L);
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

		if (isIE) {
			displayFilename = URLEncoder.encode(displayFilename, "UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=\"" + displayFilename + "\"");
		} else {
			displayFilename = new String(displayFilename.getBytes("UTF-8"), "ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" +displayFilename );
		}
	}
}
